class My_Dataset(Dataset):
    def __init__(self,filename,transform=None):
        self.filename = filename   # 文件路径
        self.transform = transform # 是否对图片进行变化
        self.image_name,self.label_image =  self.operate_file()
    def __len__(self):
        return len(self.image_name)
    def __getitem__(self,idx):
        # 由路径打开图片
        image = Image.open(self.image_name[idx])
        # 尺寸规范
        trans = transforms.Resize(size=(image_size,image_size))
        image = trans(image)
        # 获取标签值
        label = self.label_image[idx]
        # 是否需要处理
        if self.transform:
            image = self.transform(image)
            image /= 255.0  # normalize to [0,1] range
        # 转为tensor对象
        label = torch.from_numpy(np.array(label))
        return image,label
    def operate_file(self):
        train_img_dir =   self.filename
        labels = []
        imgs_path = []
        # 获取所有的文件夹路径 '../data/cat_dog_50000'的文件夹
        filenames = os.listdir(train_img_dir)  # (50000,)
        random.shuffle(filenames)
        for img_name in filenames: 
            path=os.path.join(train_img_dir, img_name) 
            imgs_path.append(path)
            if (img_name.split(".")[0] == "cat"):
                labels.append(0) # cat标签为 0
            else:
                labels.append(1) # dog标签为 1
        return imgs_path, labels
# 加载数据
train_set = My_Dataset(filename='./cat_dog_50000/', transform=transforms.ToTensor())
train_loader = DataLoader(train_set, batch_size, shuffle=True)   
